package schoolWork;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ChangeColor extends JFrame implements ActionListener {
    private JTextField textField;

    public ChangeColor() {
        setTitle("改变颜色");
        setLayout(null);

        textField = new JTextField(20);
        textField.setBounds(50, 50, 200, 30);

        JButton redButton = new JButton("红");
        redButton.setBounds(50, 100, 50, 30);
        redButton.addActionListener(this);

        JButton greenButton = new JButton("绿");
        greenButton.setBounds(120, 100, 50, 30);
        greenButton.addActionListener(this);

        JButton blueButton = new JButton("蓝");
        blueButton.setBounds(190, 100, 50, 30);
        blueButton.addActionListener(this);

        add(textField);
        add(redButton);
        add(greenButton);
        add(blueButton);

        setSize(300, 200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getActionCommand().equals("红")) {
            textField.setBackground(Color.RED);
        } else if (e.getActionCommand().equals("绿")) {
            textField.setBackground(Color.GREEN);
        } else if (e.getActionCommand().equals("蓝")) {
            textField.setBackground(Color.BLUE);
        }
    }

    public static void main(String[] args) {
        new ChangeColor();
    }
}
